package jiang.web.controller;

import java.util.HashMap;

import javax.servlet.http.HttpSession;

import jiang.app.entity.User;
import jiang.app.service.HomeService;
import jiang.app.service.UserService;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
	private static Logger logger = Logger.getLogger(HomeController.class);

	@Autowired
	HomeService homeService;
	@Autowired
	UserService userService;
	
	@RequestMapping("/")
	public String index(HttpSession s) {
		//已登录
		if(s.getAttribute("user") != null){
			return "manage";
		}
		//记住我 登录
		if(SecurityUtils.getSubject().isRemembered()){
			long userId = (long) SecurityUtils.getSubject().getPrincipal();
			s.setAttribute("user", userService.findUserById(userId));
			return "manage";
		}
		//登录界面
		return "index";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login_post(User u, boolean rememberMe, Model m, HttpSession s) {
		HashMap<String, Object> map = homeService.login(u, rememberMe);
		if (!(boolean) map.get("success")) {
			m.addAttribute("tip", "账户或密码错误");
			return "index";
		} else {
			s.setAttribute("user", map.get("user"));
			logger.info("用户登录成功");
		}
		return "manage";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession s){
		s.removeAttribute("user");
		homeService.shiroLogout();
		return "redirect:/";
	}
}
